﻿using System.Threading;
using System.Transactions;
using Moq;
using Sherwood.Content.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Sherwood.Content.Tasks.Tests
{
    
    
    /// <summary>
    ///This is a test class for TaskExecutionAgentTest and is intended
    ///to contain all TaskExecutionAgentTest Unit Tests
    ///</summary>
    [TestClass()]
    public class TaskExecutionAgentTest
    {


        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        // 
        //You can use the following additional attributes as you write your tests:
        //
        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //
        #endregion


        /// <summary>
        ///A test for OnStart
        ///</summary>
        [TestMethod()]
        [DeploymentItem("Sherwood.Content.Tasks.dll")]
        public void TestStartAndStopWithOneTaskExecution()
        {
            var mocks = new MockFactory(MockBehavior.Default);

            var taskManager = mocks.Create<ITaskManager>();
            var executionTime = DateTime.UtcNow.AddSeconds(3);
            bool taskIsExecuted = false;
            taskManager.Setup(t => t.GetNextTaskExecution()).Returns(
                () => taskIsExecuted ? DateTime.UtcNow.AddSeconds(10) : executionTime);
            var target = new TaskExecutionAgent(taskManager.Object, new DummySessionProvider()); 
            
            target.Start();

            Thread.Sleep(100);
            Assert.IsTrue(target.IsRunning);

            var task = mocks.Create<ITask>();
            executionTime = DateTime.UtcNow.AddSeconds(2);
            task.Setup(t => t.PlannedDate).Returns(() => executionTime);
            taskManager.Setup(t => t.GetExecutableTasks()).Returns(() => new[] { task.Object });

            Console.WriteLine("Raising event - " + DateTime.UtcNow);
            taskManager.Raise(t => t.TasksCreated += null, new TasksCreatedEventArgs(new []{task.Object}));

            task.Setup(t => t.Execute()).Callback(() => taskIsExecuted = true).Verifiable();

            Thread.Sleep(3000);

            Console.WriteLine("Stopping - " + DateTime.UtcNow);
            target.Stop();

            Thread.Sleep(100);

            Assert.IsTrue(taskIsExecuted);
            Assert.IsFalse(target.IsRunning);
            Assert.IsFalse(target.IsBeingStopped);
            
            mocks.Verify();
        }

    }

    public class DummySessionProvider : IDataSessionProvider, IDataSessionScope, IDataSession
    {
        public IDataSessionScope CreateScope()
        {
            return new DummySessionProvider();
        }

        public IDataSessionScope CreateScope(IsolationLevel isolationLevel)
        {
            return CreateScope();
        }

        public IDataSession CreateSession()
        {
            return new DummySessionProvider();
        }

        public void Dispose()
        {
            
        }

        public void Complete()
        {
            
        }
    }
}
